package nicg.st.util;

import nicg.st.entity.SchemeList;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Iterator;

/**
 * @author GeChen
 * @Description
 * @date 2019/11/3 23:34
 */
public class XMLUtil {
    private final static org.slf4j.Logger logger = LoggerFactory.getLogger(XMLUtil.class);

    private XMLUtil() {
    }

    /**
     * @Author Administrator
     * @Description 把document写入response 导出
     * @Date 22:45 2019/7/27
     * @Param [response, fileName, document]
     * @Return org.dom4j.io.XMLWriter
     **/
    public static String getXMLWriter(HttpServletResponse response, String fileName, Document document) {
        XMLWriter writer = null;
        OutputStream os = null;
        try {
            OutputFormat format = OutputFormat.createPrettyPrint();
            os = response.getOutputStream();

            format.setEncoding("UTF-8");

            writer = new XMLWriter(os, format);
            response.setContentType("application/xml");
            response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes(), "iso-8859-1"));

            writer.write(document);
        } catch (Exception e) {
            logger.error("导出xml时获取XMLWriter出错：" + e);
        } finally {
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    logger.error("关闭outputStream出错：" + e);
                }
            }
            if (null != writer) {
                try {
                    writer.close();
                } catch (IOException e) {
                    logger.error("关闭writer出错：" + e);
                }
            }
        }
        return ResponseUtil.getResponseString(ErrorCode.SUCCESSFUL, "successful", "1");
    }

    /**
     * @Author Administrator
     * @Description 得到的file转换成document 以解析
     * @Date 22:46 2019/7/27
     * @Param [file]
     * @Return org.dom4j.Document
     **/
    public static Document getDocumentByFile(MultipartFile file) {
        File file1 = null;
//        Document document = null;
        try {
        	InputStream ins = null;
        	ins = file.getInputStream();
        	file1 = new File(file.getOriginalFilename());
        	inputStreamToFile(ins, file1);
        	ins.close();
//            file.transferTo(file1);
//            
//            SAXReader reader = new SAXReader();
//            document = reader.read(file1);
        } catch (Exception e) {
            e.printStackTrace();
//            document = null;
//            logger.error("文件转换出错：" + e);
//        } catch (DocumentException e) {
//            document = null;
//            logger.error("读取文件出错：" + e);
        }
        Document document = null;
        try {
			SAXReader reader = new SAXReader();
			document = reader.read(file1);
			file1.delete();
		} catch (Exception e) {
			document = null;
			logger.error("读取文件出错" + e);
		}
        return document;
    }

    /**
     * @Author Administrator
     * @Description 遍历xml
     * @Date 22:47 2019/7/27
     * @Param [node, deep]
     * @Return void
     **/
    public static void listNodes(Element node, int deep) {
        Iterator<Element> iterator;
        if (node.getName().equals("评估方案信息")) {
            //            System.out.println(String.join("", Collections.nCopies(deep,"----"))+node.getName() + "：" + node.getText());
            SchemeList schemeList = new SchemeList();
            iterator = node.elementIterator();
            node = iterator.next();
            schemeList.setId(Integer.parseInt(node.getText()));
            node = iterator.next();
            schemeList.setName(node.getText());
            node = iterator.next();
            schemeList.setUserId(Integer.parseInt(node.getText()));
            node = iterator.next();
            schemeList.setDate(new Date());
            node = iterator.next();
            schemeList.setScore(Double.parseDouble(node.getText()));
            node = iterator.next();
            schemeList.setReport(node.getText());
            node = iterator.next();
            schemeList.setRemark(node.getText());
        } else if (node.getName().equals("indicator_id")) {
            System.out.println(node.getName() + node.getText());
//            Iterator<Element> iterator2 = node.elementIterator();
            iterator = node.elementIterator();
            node = iterator.next();
            System.out.println(node.getName() + ":" + node.getText());
            node = iterator.next();
            System.out.println(node.getName() + ":" + node.getText());
            node = iterator.next();
            System.out.println(node.getName() + ":" + node.getText());
            node = iterator.next();
            System.out.println(node.getName() + ":" + node.getText());
            node = iterator.next();
            System.out.println(node.getName() + ":" + node.getText());
        }
        iterator = node.elementIterator();
        while (iterator.hasNext()) {
            Element e = iterator.next();
            listNodes(e, deep + 1);
        }
    }
    
    
    private static void inputStreamToFile(InputStream ins, File file) {
    	try {
			OutputStream os = new FileOutputStream(file);
			int byteRead = 0;
			byte[] buffer = new byte[8192];
			while ((byteRead = ins.read(buffer, 0, 8192)) != -1){
				os.write(buffer, 0, byteRead);
			}
			os.close();
			ins.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
 
    
    
}
